import axios from "axios";
import store from "@/store";
import { Message } from "element-ui";
// 引入路由
import router from "@/router";

const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, //基础地址
  timeout: 5000,
}); //创建一个axios实例

// 请求拦截器 成功1 失败2
service.interceptors.request.use(
  (config) => {
    // 注入token
    // store.getters.token
    if (store.getters.token) {
      config.headers.Authorization = `Bearer ${store.getters.token}`;
    }
    return config;
  },
  (error) => {
    // 失败执行promise 终止当前promise的执行
    return Promise.reject(error);
  }
);

// 响应拦截器 成功1 失败2
service.interceptors.response.use(
  (response) => {
    const { data, message, success } = response.data;
    if (success) {
      return data;
    } else {
      Message({ type: "error", message });
      return Promise.reject(new Error(message));
    }
  },
  async (error) => {
    if (error.response.status === 401) {
      Message({
        type: "error",
        message: "会话过期",
      });
      // token过期
      await store.dispatch("user/logout"); //调用vuex中的action退出登录
      router.push("/login");
      return Promise.reject(error);
    }
    Message({
      type: "error",
      message: error.message,
    });
    return Promise.reject(error);
  }
);

export default service;
